<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/14
 * Time: 10:02
 */

namespace app\api\controller;

use app\admin\controller\BaseAdminController;
use app\api\model\GoodsRule;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;
use app\api\model\Goods as GoodsModel;

class Goods extends BaseAdminController
{

    /**
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Response
    {
        $param = Request::param();
        $sql   = new GoodsModel();
        //商品编号和名称
        if (request()->param('name', 0)) {
            $map  = [
                ['name', 'like', '%' . $param['name'] . '%'],
            ];
            $map1 = [
                ['no', 'like', '%' . $param['name'] . '%'],
            ];
            $sql  = $sql->whereOr([$map, $map1]);
        }
        //商品分类
        if (request()->param('goods_cate_id', 0)) {
            $sql = $sql->where('goods_cate_id', $param['goods_cate_id']);
        }
        $sql = $sql->where('status',1);
        $count = $sql->count();
        $sql   = $sql->page($param['page'], $param['limit']);
        $list  = $sql->order('id  Desc')->field('id,name,img,no,spec_type')->select()->each(function ($item) {
            $rule                = $item->goodsRule()->order("money")->find();
            $item->goods_rule_id = $rule ? $rule->id : 0;
            $item->money         = $rule ? $rule->money : 0;
            $item->quantity      = $rule ? $rule->quantity : 0;
        });
        return $this->success('获取成功', compact('count', 'list'));
    }

    /**
     * 获取多规格
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function rule(): Response
    {
        $param = Request::param();
        $sql   = new GoodsRule();
        $sql   = $sql->withSearch('goods_id', $param)->where('status',1);
        $list  = $sql->field('id,money,spec_name')->select();
        return $this->success('获取成功', $list);
    }
}